const path = require('path');
const chalk = require('chalk');
const fse = require('fs-extra');
const rimraf = require('rimraf');
const globAsync = require('fast-glob');
const svgo = require('svgo');

const inputDir = path.resolve(__dirname, './src/svgs');
const outputDir = path.resolve(__dirname, './src/components');

/**
 * Converts directory separators to slashes, so the path can be used in fast-glob.
 */
function normalizePath(pathToNormalize) {
  return pathToNormalize.replace(/\\/g, '/');
}

async function generateIndex() {
  const files = await globAsync(normalizePath(path.join(outputDir, '*.tsx')));
  const index = files
    .map((file) => {
      const typename = path.basename(file).replace('.tsx', '');
      return `export { default as ${typename}Icon } from './${typename}';\n`;
    })
    .join('');

  fse.writeFileSync(path.join(outputDir, 'index.ts'), index);
}

async function createIcons() {
  rimraf.sync(`${outputDir}/*.tsx`);

  const tsxFiles = [];
  const svgPaths = await globAsync(
    normalizePath(path.join(inputDir, '**/*.svg')),
  );

  svgPaths.forEach((svgPath) => {
    const data = fse.readFileSync(svgPath, { encoding: 'utf8' });
    const iconName = path.basename(svgPath).replace('.svg', '');
    const result = svgo.optimize(data);
    const pathData = result.data.match(/<svg[^>]+?>([^$]+?)<\/svg>/)[1];

    tsxFiles.push({
      name: iconName,
      content: `// Automatically generated by cli tools, please do not modify this file directly
import createSvgIcon from '../utils/createSvgIcon';

export default createSvgIcon(
  '${pathData}',
  '${iconName}Icon',
);
`,
    });
  });

  tsxFiles.forEach(({ name, content }) => {
    console.log(`${chalk.blue(name)} icon created`);
    const absDestPath = path.join(outputDir, `${name}.tsx`);
    fse.writeFileSync(absDestPath, content);
  });

  generateIndex();
}

createIcons();
